using System;
using System.Collections.Generic;

namespace DataBroker.Dao
{
    /// <summary>
    /// Summary description for ObjectPropertyComparer.
    /// </summary>
    public class ObjectPropertyComparer : IComparer<Entity>
    {
        private string PropertyName;

        /// <summary>
        /// Provides Comparison opreations.
        /// </summary>
        /// <param name="propertyName">The property to compare</param>
        public ObjectPropertyComparer( string propertyName)
        {
            PropertyName = propertyName;
        }

        /// <summary>
        /// Compares 2 objects by their properties, given on the constructor
        /// </summary>
        /// <param name="x">First value to compare</param>
        /// <param name="y">Second value to compare</param>
        /// <returns></returns>
        public int Compare(Entity x, Entity y)
        {
            EntityPropertyDescriptor mpd = new EntityPropertyDescriptor(PropertyName);
            object a =  mpd.GetValue(x);
            object b = mpd.GetValue(y);

            if ( a != null && b == null )
                return 1;

            if ( a == null && b != null )
                return -1;

            if ( a == null && b == null )
                return 0;

            return ((IComparable)a).CompareTo(b);
        }
    }
}